import BaseMctApi from '@/framework/infra/base/BaseMctApi'
import SpuEntity from '@/feature/pdt/domain/SpuEntity'
import SpuPropertyCollection from "@/feature/pdt/domain/SpuPropertyCollection";
import SpuProperty from "@/feature/pdt/domain/SpuProperty";
import SpuDetailEntity from "@/feature/pdt/domain/SpuDetailEntity";
import {propertyApi} from "@/feature/pdt/infra/api/propertyApi";

class SpuApi extends BaseMctApi {
  constructor() {
    super('spu')
  }

  list(params) {
    return super.list(params).then(data => {
      data.data = data.data.map(el => new SpuEntity(el))
      return data
    })
  }

  online(id) {
    return this.post('online', {id})
  }

  offline(id) {
    return this.post('offline', {id})
  }

  querySpuServiceList() {
    return this.get('service-list')
  }

  create(data) {
    return this.post('create', data)
  }

  update(data) {
    return this.post('update', data)
  }

  detail(id) {
    return this.get('detail', {id}).then(async data => {
      data.propList = SpuPropertyCollection.from(data.propList.map(el => new SpuProperty(el, false)))
      let selectableProperties = null
      let salePropList
      if (data.salePropSource === 1) { // 自定义属性
        selectableProperties = await propertyApi.commonSaleProps()
        salePropList = data.salePropList.map((el, idx) => {
          el.title = (selectableProperties.find(i => i.id === el.id) || {}).title || ''
          el.deletable = true
          el.uploadPicFlag = idx === 0 ? 1 : 0
          // el.isUploadPic =
          return new SpuProperty(el, true, data.skuList, true)
        })
      } else {
        salePropList = data.salePropList.map(el => new SpuProperty(el, true, data.skuList, false))
      }
      data.salePropList = SpuPropertyCollection.from(salePropList, true, data.skuList, selectableProperties)
      return new SpuDetailEntity(data)
    })
  }
}

export const spuApi = new SpuApi()
